"""
工具4：职位查询工具
功能：查询职位信息
"""
import json
import logging
from langchain.tools import BaseTool

logger = logging.getLogger(__name__)


class JobQueryTool(BaseTool):
    """职位查询工具"""
    
    name: str = "job_query_tool"
    description: str = """
        查询职位信息。
        
        输入参数（JSON字符串）：
        {
            "job_id": 123,  // 职位ID（可选）
            "keyword": "Python工程师"  // 关键词（可选）
        }
        
        返回：职位详情列表
        """
    
    def _run(self, job_id: str = None, keyword: str = None) -> str:
        try:
            from home.models import Jobposting
            
            if job_id:
                try:
                    job_id_int = int(job_id)
                    jobs = Jobposting.objects.filter(id=job_id_int).select_related('company', 'city')
                except (ValueError, TypeError):
                    return self._error_response("无效的job_id")
            elif keyword:
                jobs = Jobposting.objects.filter(
                    title__icontains=keyword
                ).select_related('company', 'city')[:10]
            else:
                return self._error_response("请提供job_id或keyword")
            
            job_list = []
            for job in jobs:
                job_list.append({
                    "id": job.id,
                    "title": job.title,
                    "company": job.company.name if job.company else "",
                    "city": job.city.name if job.city else "",
                    "salary": job.money,
                    "education": job.education,
                    "description": job.description[:200],
                    "tags": job.label
                })
            
            return json.dumps({
                "success": True,
                "data": job_list,
                "message": f"找到{len(job_list)}个职位"
            }, ensure_ascii=False)
            
        except Exception as e:
            logger.error(f"职位查询失败: {str(e)}")
            return self._error_response(str(e))
    
    def _error_response(self, error: str) -> str:
        return json.dumps({
            "success": False,
            "error": error,
            "message": "查询失败"
        }, ensure_ascii=False)
    
    async def _arun(self, *args, **kwargs):
        raise NotImplementedError()


